'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IConfigJwt, IDifference } from '@/interfaces';
import { updateJwtConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateConfigJwt({
  source,
  translatedFields,
}: {
  source: IConfigJwt;
  translatedFields: PrefixedTTranslatedFields<'configAdminPage'>;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    tokenExp: string;
    refreshTokenExp: string;
    generateNewKey?: boolean;
  }>({
    tokenExp: source.tokenExp ?? '',
    refreshTokenExp: source.refreshTokenExp ?? '',
    generateNewKey: false,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateJwtConfigMutation = useMutation(updateJwtConfig);

  useEffect(() => {
    const diffData = diff(
      {
        tokenExp: source.tokenExp ?? '',
        refreshTokenExp: source.refreshTokenExp ?? '',
        generateNewKey: false,
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const data = getDiffData(differenceData);

      if (data.tokenExp && !data.tokenExp.startsWith('PT')) {
        data.tokenExp = 'PT' + data.tokenExp;
      }
      if (data.refreshTokenExp && !data.refreshTokenExp.startsWith('PT')) {
        data.refreshTokenExp = 'PT' + data.refreshTokenExp;
      }

      await updateJwtConfigMutation.mutateAsync({
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateJwtConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function checkForm() {
    const { tokenExp, refreshTokenExp } = form;

    if (
      !(
        !tokenExp.includes('H') ||
        !tokenExp.includes('M') ||
        !tokenExp.includes('S')
      )
    ) {
      throw translatedFields.config.jwt.tokenInvalidFormat;
    }

    if (
      !(
        !refreshTokenExp.includes('H') ||
        !refreshTokenExp.includes('M') ||
        !refreshTokenExp.includes('S')
      )
    ) {
      throw translatedFields.config.jwt.tokenInvalidFormat;
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'generateNewKey') {
      setForm({ ...form, generateNewKey: value === 'true' });
    } else {
      setForm({ ...form, [name]: value.trim().toUpperCase() });
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.config.jwt.tokenExp}
          </label>
          <input
            type="text"
            className="form-control"
            name="tokenExp"
            value={form.tokenExp}
            onChange={onChangeForm}
            aria-describedby="tokenExp"
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.config.jwt.refreshTokenExp}
          </label>
          <input
            type="text"
            className="form-control"
            name="refreshTokenExp"
            value={form.refreshTokenExp}
            onChange={onChangeForm}
            aria-describedby="refreshTokenExp"
          />
        </div>

        <div>
          <label className="form-label">
            {' '}
            {translatedFields.config.jwt.generateNewKey}
          </label>
          <select
            name="generateNewKey"
            value={form.generateNewKey + ''}
            onChange={onChangeForm}
            className="form-select"
            aria-label="generateNewKey"
          >
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        </div>

        <button
          type="submit"
          disabled={updateJwtConfigMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateJwtConfigMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
